//
//  STHomeVC.swift
//  Demo-04-TabBar的尝试
//
//  Created by 苏统世 on 16/5/9.
//  Copyright © 2016年 SuTon. All rights reserved.
//

import UIKit

import SVPullToRefresh

/// 下拉提示视图高度
private let TipLabelHeight:CGFloat = 44

class STHomeVC: STBasicTableVC {

    var homeDatas:[STData]?{
        didSet{
            self.tableView.reloadData()
        }
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        
        if !STUserAccountViewModel.shareManager.isUserLogin {
            return
        }
        /// 设置navigationItem
        setupNavigation()
        /// tableView设置
        setTableView()
    }
    // MARK: - 加载微博信息 刷新设置
    private func loadData(){
        //
        let since_id = homeDatas?.first?.id ?? 0
        
//        let since_id:Int64 = 2
        
        STDataViewModel.shareManager.loadMessages(since_id, max_id: 0) { (datas) -> () in
            let count = datas.count ?? 0
            // 判断是下拉刷新才显示
            if since_id > 0 {
                self.showTipLabel(count)
            }
            if count == 0{
                return
            }
            if since_id == 0{
                // 加载20条微博, 直接显示这20条数据
                self.homeDatas = datas
                
                self.tableView.addInfiniteScrollingWithActionHandler({ () -> Void in
                    self.loadMoreData()
                })
            }else{
                // since_id加载比某条新的微博,下拉刷新
                // 获取到的新的微博数组添加到现有数组的前面
                self.homeDatas = datas + self.homeDatas!
            }
            STPrint(items: "当前数组中有\(self.homeDatas?.count)条数据")
        }
    }
    // MARK: - 加载更多信息
    private func loadMoreData(){
        let max_id = self.homeDatas?.last?.id ?? 0
        STDataViewModel.shareManager.loadMessages(0, max_id: max_id) { (datas) -> () in
            self.tableView.infiniteScrollingView.stopAnimating()
            let count = datas.count ?? 0
            if count == 0{ return }
            self.homeDatas = self.homeDatas! + datas
        }
    }
    
    
    // MARK: - 设置下拉刷新的提示label
    private func showTipLabel(count: Int) {
        let text = count == 0 ? "没有新的微博了" : "加载了 \(count) 条新微博"
        
        tipLabel.text = text
        
        // 当动画还没有回去,又指定动画会出现动画叠加
        // 在做动画之前,将之前的动画移除
        // UIView动画最终也是核心动画
        let anim = self.tipLabel.layer.animationKeys() // 获取在layer上的所有核心动画
        // 如果找到了动画说明有动画还没做完,移除它
        if anim != nil {
            STPrint(items: "之前有动画没做完,移除: \(anim)")
            self.tipLabel.layer.removeAllAnimations()
        }
        let duration = 0.75
        UIView.animateWithDuration(duration, animations: { () -> Void in
            self.tipLabel.frame.origin.y = TipLabelHeight
            }) { (_) -> Void in
                // 动画完了,还要做回去的动画,延迟回去的动画
                UIView.animateKeyframesWithDuration(duration, delay: 1, options: UIViewKeyframeAnimationOptions(rawValue: 0), animations: { () -> Void in
                    self.tipLabel.frame.origin.y = -64
                    }, completion: nil)
        }
    }
    // MARK: - 对 tableView 的设置
    private func setTableView(){
        // 注册 tableViewCell
        tableView.registerClass(STTableViewCell.self, forCellReuseIdentifier: "cell")
        tableView.estimatedRowHeight = 100
        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.separatorStyle=UITableViewCellSeparatorStyle.None
        tableView.backgroundColor=UIColor.lightGrayColor()
        /// 加入下拉刷新 view
        tableView.addSubview(pullDownRefreshView)
        
        pullDownRefreshView.callbackBlock={
            dispatch_async(dispatch_get_global_queue(0, 0), { () -> Void in
                /// do something with delay
                NSThread.sleepForTimeInterval(2)
                dispatch_async(dispatch_get_main_queue(), { () -> Void in
                    
                    self.pullDownRefreshView.endRefreshing()
                    /// 加载微博信息
                    self.loadData()
                })
            })
        }
        pullDownRefreshView.beginRefreshing()
    }
    
    // MARK: - 设置navigationItem
    private func setupNavigation(){
        navigationItem.leftBarButtonItem=UIBarButtonItem(imageName: "navigationbar_friendsearch", target: self, action: Selector("didClickMenuButton:"), touchStype: UIControlEvents.TouchUpInside)
        
        navigationItem.rightBarButtonItem=UIBarButtonItem(imageName: "navigationbar_pop", target: self, action: Selector("didClickSettingButton:"), touchStype: UIControlEvents.TouchUpInside)
        
        let buttonView = STButton(type: UIButtonType.Custom)
        let userName = STUserAccountViewModel.shareManager.userAccount?.screen_name
        buttonView.setTitle(userName ?? "用户昵称", forState: UIControlState.Normal)
        buttonView.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
        buttonView.titleLabel?.font = UIFont.systemFontOfSize(15)
        buttonView.setImage(UIImage(named: "navigationbar_arrow_down"), forState: UIControlState.Normal)
        buttonView.sizeToFit()
        buttonView.addTarget(self, action: Selector("didClickTitleView:"), forControlEvents: UIControlEvents.TouchUpInside)
        navigationItem.titleView=buttonView
        
        navigationController?.navigationBar.insertSubview(tipLabel, atIndex: 0)
    }
    // MARK: - Button Action
    @objc private func didClickTitleView(button:UIButton){
        STPrint(items: "点击了Home【TitleView】按钮")
        
        button.selected = !button.selected
        STPrint(items: "\(button.selected)")

        UIView.animateWithDuration(0.35) { () -> Void in
            button.imageView?.transform = button.selected ? CGAffineTransformMakeRotation(CGFloat(M_PI-0.001)) : CGAffineTransformIdentity
        }
    }
    @objc private func didClickMenuButton(menuBtn:UIBarButtonItem){
        STPrint(items: "点击了Home【注册】按钮")
        
    }
    @objc private func didClickSettingButton(settingBtn:UIBarButtonItem){
        STPrint(items: "点击了Home【加载本地json数据】")
        // 加载本地json数据
        let file = NSBundle.mainBundle().pathForResource("statuses", ofType: "json")!
        let data = NSData(contentsOfFile: file)!
        let json = try! NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(rawValue: 0))
        STPrint(items: "解析本地数据: \(json)")
    }
    
    
    // MARK: - 懒加载刷新 view
    private lazy var pullDownRefreshView:STPullDownRefreshView=STPullDownRefreshView()
    // MARK: - 下拉提示的label
    private lazy var tipLabel: UILabel = {
        let label = UILabel()
        
        // 设置
        label.backgroundColor = UIColor.cyanColor()
        label.font = UIFont.systemFontOfSize(18)
        label.textColor = UIColor.blackColor()
        label.textAlignment = NSTextAlignment.Center
        
        label.frame = CGRect(x: 0, y: -20 - TipLabelHeight, width: UIScreen.mainScreen().bounds.width, height: TipLabelHeight)
        
        return label
    }()
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

// MARK: - 扩展，代理方法
extension STHomeVC{
    // MARK: -  UITableViewDataSource
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return homeDatas?.count ?? 0
    }
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCellWithIdentifier("cell") as! STTableViewCell
        cell.data = self.homeDatas![indexPath.row]
        return cell
    }
    
    // MARK: - UITableViewDelegate
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        // 先判断有没有缓存的行高
        // 获取到indexPath.row的模型
        let status = self.homeDatas![indexPath.row]
        if let rowHeight=status.cellHeight{
            return rowHeight
        }
        let cell=tableView.dequeueReusableCellWithIdentifier("cell") as! STTableViewCell
        /// 指定模型计算高
        cell.data=status
        let rowHeight=cell.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize).height
        status.cellHeight=rowHeight

        return rowHeight
    }
    
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        tableView.deselectRowAtIndexPath(indexPath, animated: true)
    }
    
    
}


